package com.relytosoft.mizar.media.display.services.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.StrUtil;
import com.relytosoft.dubhe.common.core.object.ResponseResult;
import com.relytosoft.dubhe.common.core.utils.BeanCopyUtils;
import com.relytosoft.dubhe.common.log.annotation.OpLog;
import com.relytosoft.dubhe.common.log.enums.OpTypeEnum;
import com.relytosoft.mizar.media.common.config.properties.MizarTransProperties;
import com.relytosoft.mizar.media.common.utils.TransRequestUtil;
import com.relytosoft.mizar.media.display.api.entity.Rotagroup;
import com.relytosoft.mizar.media.display.api.entity.RotagroupChannel;
import com.relytosoft.mizar.media.display.api.feign.VideoTransFeignService;
import com.relytosoft.mizar.media.display.api.pojo.dto.RotagroupDto;
import com.relytosoft.mizar.media.display.api.pojo.query.RotaPlayQuery;
import com.relytosoft.mizar.media.display.api.pojo.vo.RotagroupChannelVo;
import com.relytosoft.mizar.media.display.api.pojo.vo.RotagroupVo;
import com.relytosoft.mizar.media.display.api.pojo.vo.VideoPlayVo;
import com.relytosoft.mizar.media.display.services.service.RotagroupChannelService;
import com.relytosoft.mizar.media.display.services.service.RotagroupService;
import com.relytosoft.mizar.media.display.services.utils.ResponseUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * 巡检
 *
 * @Author SunLi
 * @Date: 2022/4/12 11:40
 * @Version 1.0
 */
@Validated
@RestController
@RequestMapping("/display/rotagroup")
@Api(tags="巡检相关接口")
public class RotagroupController {

    @Resource
    private RotagroupService rotagroupService;
    @Resource
    private RotagroupChannelService rotagroupChannelService;
    @Resource
    private MizarTransProperties transProperties;
    @Resource
    private VideoTransFeignService transFeignService;

    @GetMapping(value = "/list")
    @SaCheckPermission("display:rotagroup:list")
    @ApiOperation("获得巡检组列表信息")
    public ResponseResult<List<RotagroupVo>> selectRotagroupList(@ApiParam("名称")@RequestParam(required = false) String name) {
        return ResponseResult.ok(rotagroupService.selectRotagroupList(name));
    }
    @GetMapping(value = "/treelist")
    @SaCheckPermission("display:rotagroup:list")
    @ApiOperation("获得巡检组列表树信息")
    public ResponseResult<List<Tree<Integer>>> selectRotagroupTreeList(@ApiParam("名称")@RequestParam(required = false) String name) {
        return ResponseResult.ok(rotagroupService.buildRotagroupListTree(rotagroupService.selectRotagroupList(name)));
    }
    @PostMapping(value = "/insert")
    @SaCheckPermission("display:rotagroup:insert")
    @ApiOperation("添加巡检组信息")
    @OpLog(msg = "添加巡检组信息", opType = OpTypeEnum.INSERT)
    public ResponseResult<Void> insertRotagroup(@Valid @RequestBody RotagroupDto rotagroupDto) {
        Rotagroup entity= BeanCopyUtils.copy(rotagroupDto,Rotagroup.class);
        String mes = validate(entity,rotagroupDto.getRotagroupChannelList());
        if (!StrUtil.isEmpty(mes)) {
            return ResponseResult.fail(mes);
        }
        entity.setId(null);
        entity.setStatus(1);
        if(entity.getSort()==null){
            entity.setSort(1);
        }
        boolean result = rotagroupService.insertRotagroup(entity,rotagroupDto.getRotagroupChannelList());
        if (result) {
            return ResponseResult.ok();
        }
        return ResponseResult.fail();
    }

    @PutMapping(value = "/update")
    @SaCheckPermission("display:rotagroup:update")
    @ApiOperation("修改巡检组信息")
    @OpLog(msg = "修改巡检组信息", opType = OpTypeEnum.UPDATE)
    public ResponseResult<Void> updateRotagroup(@Valid @RequestBody RotagroupDto rotagroupDto) {
        Rotagroup entity= BeanCopyUtils.copy(rotagroupDto,Rotagroup.class);
        String mes = validate(entity,rotagroupDto.getRotagroupChannelList());
        if (!StrUtil.isEmpty(mes)) {
            return ResponseResult.fail(mes);
        }
        if(entity.getSort()==null){
            entity.setSort(1);
        }
        boolean result = rotagroupService.updateRotagroup(entity,rotagroupDto.getRotagroupChannelList());
        if (result) {
            return ResponseResult.ok();
        }
        return ResponseResult.fail();
    }

    @PutMapping(value = "/updatestatus/{id}/{status}")
    @SaCheckPermission("display:rotagroup:updatestatus")
    @ApiOperation("修改巡检组信息状态")
    @OpLog(msg = "修改巡检组信息状态", opType = OpTypeEnum.SET)
    public ResponseResult<Void> setRotagroupStatus(@PathVariable int id,@PathVariable int status) {
        int result = rotagroupService.updateRotagroupStatus(id, status);
        if (result>0) {
            return ResponseResult.ok();
        }
        return ResponseResult.fail();
    }

    @GetMapping(value = "/{id}")
    @SaCheckPermission("display:rotagroup:getinfo")
    @ApiOperation("获得巡检组信息")
    public ResponseResult<RotagroupChannelVo> getRotagroup(@PathVariable int id){
        Rotagroup entity=rotagroupService.getById(id);
        RotagroupChannelVo rotagroupChannelVo=BeanCopyUtils.copy(entity,RotagroupChannelVo.class);
        rotagroupChannelVo.setRotagroupChannelList(rotagroupChannelService.selectRotagroupChannelList(id));
        return ResponseResult.ok(rotagroupChannelVo);
    }
    @PutMapping(value = "/getplayurl")
    @ApiOperation("获得巡检通道播放URL")
    @OpLog(msg = "视频巡检", opType = OpTypeEnum.OTHER)
    public ResponseResult<List<VideoPlayVo>> selectPlayUrl(@ApiParam("巡检组通道")@RequestBody RotaPlayQuery rotaPlayRequest){
        List<VideoPlayVo> rotaPlayVoList=new ArrayList<>();
        //webrtc播放URL
        String strTmp="http://%s/index/api/webrtc?app=%s&stream=%s&type=play";
        //rtmp URL rtmp://ip/app/stream
        //rtmp对应的http-flv、websocket URL
        //ws URL  ws://ip/app/stream.app.flv 示例ws://127.0.0.1/live/0.live.flv
        //flv URL http://ip/app/stream.app.flv示例http://127.0.0.1/live/0.live.flv
        if(rotaPlayRequest!=null&&rotaPlayRequest.getPlayInfo().size()>0){
            rotaPlayRequest.getPlayInfo().forEach(e->{
                VideoPlayVo rotaPlayVo=new VideoPlayVo();
                if(StrUtil.isNotBlank(e.getStreamRtspUrl())&&e.getChannelId()!=null){
                    //将RTSP URL经转码服务器进行拉流
                    String res= TransRequestUtil.handlerResponse(transFeignService.addStreamProxy(transProperties.getAppSecret(),"0","live",e.getChannelId().toString(),e.getStreamRtspUrl(),1,0));
                    //封装为前端可播放的URL
                    rotaPlayVo.setPlayStreamUrl(String.format(strTmp,transProperties.getPlayUrl(),"live",e.getChannelId()));
                    rotaPlayVo.setPlayStreamKey(ResponseUtils.getStreamProxyKey(res));
                }
                else{
                    rotaPlayVo.setPlayStreamUrl("");
                    rotaPlayVo.setPlayStreamKey("");
                }
                rotaPlayVo.setGroupId(rotaPlayRequest.getGroupId());
                rotaPlayVo.setChannelId(e.getChannelId());

                rotaPlayVoList.add(rotaPlayVo);
            });
        }
        return ResponseResult.ok(rotaPlayVoList);
    }

    private String validate(Rotagroup entity,List<RotagroupChannel> rotagroupChannelList) {
        if(!rotagroupService.checkRotagroupNameUnique(entity)){
            return "分组名称已存在！";
        }
        if(CollUtil.isEmpty(rotagroupChannelList)){
            return "请添加通道！";
        }
        return "";
    }
}
